﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dos.ORM;
using Model;

namespace Logic
{
    public class SaleRecLogic
    {
        public static int Insert(TB_Sale_Rec saleRec)
        {
            if (Exists(saleRec.RecDate, saleRec.SaleAccount))
            {

                return DB.Context.Update<TB_Sale_Rec>(saleRec, d => d.RecDate == saleRec.RecDate && d.SaleAccount == saleRec.SaleAccount);
            }
            else
            {
                return DB.Context.Insert<TB_Sale_Rec>(saleRec);
            }
        }

        public static bool Exists(string feeDate, string saleAccount)
        {
            return DB.Context.Exists<TB_Sale_Rec>(d => d.RecDate == feeDate && d.SaleAccount == saleAccount);
        }

        public static List<TB_Sale_Rec> GetRecByMonth(string recMonth)
        {
            string month = DateTime.Parse(recMonth + "-01").AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            return DB.Context.From<TB_Sale_Rec>().Where(d => d.RecDate == month)
                .ToList();

        }

        public static int GetAllSucCount(string recMonth)
        {
            object obj = DB.Context.FromSql("select sum(recsuccount) from TB_Sale_Rec where left(recdate,7)='" + recMonth + "'").ToScalar();

            if (obj == null || obj == DBNull.Value)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
           
        }

        public static int GetAllFailCount(string recMonth)
        {
            object obj = DB.Context.FromSql("select sum(recfailcount) from TB_Sale_Rec where left(recdate,7)='" + recMonth + "'").ToScalar();
            if (obj == null || obj == DBNull.Value)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
    }
}
